import { useCallback, useEffect, useRef } from "react";

/**
 * fn动态保持最新且不会重新创建
 * @param fn 需要防抖的函数
 * @returns 新的已防抖的函数
 */
export function useCallbackRef<T extends (...args: never[]) => unknown>(
  fn?: T
): T {
  const fnRef = useRef(fn);
  // 每次渲染后执行赋值操作 确保fn是最新的
  useEffect(() => {
    fnRef.current = fn;
  });
  return useCallback(((...args) => fnRef.current?.(...args)) as T, []);
}
